package operator;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Classname Operator
 * @Author happytaohaha
 * @Date 2020/2/28
 * @Description 将中缀式转为后缀式
 */
public class Operator {


    /**
     * 保证输入的是正确的中缀式。
     * 如果是数字不为一个的话，前置加个处理器，将操作数和操作符号分开。
     * 掌握好操作符号的优先级，如何放入栈即可。
     * @param operation
     * @return
     */
    public static String trans(String operation) {
        Stack<Character> stack = new Stack<Character>();
        List<Character> list = new ArrayList<Character>();
        for (int i = 0; i < operation.length(); i++) {
            char a = operation.charAt(i);
            switch (a) {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    list.add(a);
                    break;
                case '(':
                    stack.push(a);
                    break;
                case ')':
                    while (!stack.peek().equals('(')) {
                        list.add(stack.pop());
                    }
                    if (stack.peek().equals('(')) {
                        stack.pop();
                    }
                    break;
                case '+':
                case '-':
                    if (stack.empty() || stack.peek().equals('(')) {
                        stack.push(a);
                    } else if (stack.peek().equals('-') || stack.peek().equals('+')) {
                        list.add(a);
                    }
                    break;
                case '*':
                case '/':
                    if (stack.peek().equals('*') || stack.peek().equals('/')) {
                        list.add(a);
                    }else{
                        stack.push(a);
                    }
                    break;
                default:
                    break;
            }
        }
        while (stack.size() > 0) {
            char a;
            switch (a = stack.pop()) {
                case '(':
                    break;
                default:
                    list.add(a);
                    break;
            }
        }
        return list.toString();
    }


    public static void main(String[] args) {
        System.out.println(trans("1+(2+3*4)"));
    }
}
